package com.cdream.basic.algorithm.leetcode.tree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Offer37 {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        return serialize(root, "");
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        return serialize(new ArrayList<>(Arrays.asList(data.split(","))));
    }

    String serialize(TreeNode root, String res) {
        if (root == null) {
            res += "null,";
            return res;
        } else {
            res += root.val + ",";
        }

        res = serialize(root.left, res);
        res = serialize(root.right, res);
        return res;
    }

    TreeNode serialize(List<String> list) {
        if (list.get(0).equals("null")) {
            list.remove(0);
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(list.get(0)));
        list.remove(0);
        root.left = serialize(list);
        root.right = serialize(list);

        return root;
    }

    public static void main(String[] args) {
        new Offer37().deserialize("1,2,3,null,null,4,5");
    }
}
